package cn.memset.code.functionInterface;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class FunctionExample {
    public static void main(String[] args) {
        testFunctionWithLambda();
    }

    public static void testFunctionWithLambda() {
        // 构建一个HashMap，key是某个单词，value是单词的字母长度
        Map<String, Integer> wordMap = new HashMap<>();
        Integer wordLen = wordMap.computeIfAbsent("hello", s -> s.length());
        System.out.println(wordLen);
        System.out.println(wordMap);
    }

    public static void testFunctionWithMethodReference() {
        Map<String, Integer> wordMap = new HashMap<>();
        Integer wordLen = wordMap.computeIfAbsent("hello", String::length);
        System.out.println(wordLen);
        System.out.println(wordMap);
    }

    public static void testBiFunctionWithLambda() {
        Map<String, Integer> wordMap = new HashMap<>();
        wordMap.put("hello", 5);
        wordMap.put("world", 5);
        wordMap.put("on", 2);
        wordMap.put("at", 2);

        wordMap.replaceAll((key, value) -> {
            if ("on".equals(key) || "at".equals(key)) {
                return 0;
            } else {
                return value;
            }
        });

        System.out.println(wordMap);
    }

    public static void testFunctionAndThen() {
        // wordLen 计算单词的长度
        Function<String, Integer> wordLen = s -> s.length(); // 等同于 s -> { return s.length(); }

        // effectiveWord 单词长度大于等于4，才认为是有效单词
        Function<Integer, Boolean> effectiveWordLen = len -> len >= 4;

        // Function<String, Integer> 和 Function<Integer, Boolean> 组合得到一个新的 Function<String, Boolean> ，
        // 像是消消乐： <String, Integer> 遇到了 <Integer, Boolean> ，消去了 Integer 类型后，得到了 <String, Boolean> 。
        Function<String, Boolean> effectiveWord = wordLen.andThen(effectiveWordLen);

        Map<String, Boolean> wordMap = new HashMap<>();
        wordMap.computeIfAbsent("hello", effectiveWord);
        wordMap.computeIfAbsent("world", effectiveWord);
        wordMap.computeIfAbsent("on", effectiveWord);
        wordMap.computeIfAbsent("at", effectiveWord);

        System.out.println(wordMap);
    }
}
